slider = {
    pages = {},
    x = 0,
    y = 0,
    width = 300,
    height = 300,
    getPosition = function ()
        return slider.x, slider.y
    end,
    getWidth = function ()
        return slider.width
    end,
    offset = 0,
    newOffset = 0,
    isDisable = false,
    _speed = 0,
    update = function (dt) 
        if slider.isDisable then return end
        if slider.setup then
            slider.setup(
                slider.setPosition,
                slider.setSize, 
                slider.addPage
            )
            slider.setup = nil
        end
        
        if gesture.isSwiping() then
            gesture._speed = 0
            local x, y = gesture.getOrigin() 
            if 
                x > slider.x and x < slider.x + slider.width and
                y > slider.y and y < slider.y + slider.height
            then
                slider.newOffset = gesture.getOffset()
            end
        else
            if slider.newOffset ~= 0 then
                slider._speed = math.min(gesture.getSpeed(), 500)
                slider._speed = math.max(gesture._speed,-500)
                slider.offset = math.min(slider.offset + slider.newOffset, 0)
                slider.offset = math.max(slider.offset, (#slider.pages-1)*slider.width*-1)
                slider.newOffset = 0
            end
            if slider._speed > 50 or slider._speed < -50 then
                slider._speed = slider._speed - slider._speed/math.abs(slider._speed)*dt*100
                slider.offset = math.min(slider.offset + slider._speed*0.05, 0)
                slider.offset = math.max(slider.offset, (#slider.pages-1)*slider.width*-1)
            end

            local page, pageOffset = math.modf(slider.getCurrentPage())
            if pageOffset > 0.5 then
               slider.offset = math.max(slider.offset - dt*200, (page+1)*slider.width*-1) 
            elseif pageOffset < 0.5 then
                slider.offset = math.min(slider.offset + dt*200, page*slider.width*-1)
            end
        end

        for page, callback in ipairs(slider.pages) do
            callback(
                slider.x+slider.getWidth()*(page-1)+slider.offset+slider.newOffset,
                slider.y,
                slider.width,
                slider.height
            )    
        end
    end,
    addPage = function (callback)
        table.insert(slider.pages, callback) 
    end,
    enable = function ()
        slider.isDisable = false
    end,
    disable = function ()
        slider.isDisable = true
    end,
    setup = function (slider, add) end
}

-- set the slider position
function slider.setPosition (x, y)
    slider.x = x or slider.x
    slider.y = y or slider.y
end

-- set the slider size
function slider.setSize (w, h)
    slider.width = w
    slider.height = h
end

-- get the current focus page
function slider.getCurrentPage ()
    return math.abs(slider.offset/slider.width)
end
